package com.rockcent.job.task;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rockcent.common.utils.DateFormatUtils;
import com.rockcent.common.utils.DateUtils;
import com.rockcent.helper.WxAppHelper;
import com.rockcent.mall.lib.domain.MiniAppConfig;
import com.rockcent.mall.lib.domain.WxappVisitPage;
import com.rockcent.mall.lib.domain.WxappVisitPageLog;
import com.rockcent.mall.lib.dto.MiniVisitPageDto;
import com.rockcent.mall.lib.dto.VisitPageDto;
import com.rockcent.mall.lib.repository.MiniAppConfigRepository;
import com.rockcent.mall.lib.repository.WxappVisitPageLogRepository;
import com.rockcent.mall.lib.repository.WxappVisitPageRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by marco on 2017/8/3.
 */
@Component
public class WxappVisitPageTask {

    final Logger log = LoggerFactory.getLogger(WxappVisitPageTask.class);

    @Autowired
    private MiniAppConfigRepository miniAppConfigRepository;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private WxappVisitPageLogRepository wxappVisitPageLogRepository;
    @Autowired
    private WxappVisitPageRepository wxappVisitPageRepository;

    /**
     * 同步小程序的访问记录
     * 0 0 5 * * ? 每天凌晨5:00执行任务
     */
    @Scheduled(cron = "${job.syncData.cron}")
    @Transactional(propagation = Propagation.REQUIRED)
    public void syncData() {
        List<MiniAppConfig> configList = miniAppConfigRepository.findAll();
        String currentDate=DateUtils.getCurrentTime(DateFormatUtils.DATE_FORMAT1);
        String beginDate=DateUtils.addDayToDate(-1,currentDate,DateFormatUtils.DATE_NOFUll_FORMAT);
        String endDate=beginDate;
        log.info("endDate:{}",endDate);
        if(configList!=null) {
            for(MiniAppConfig miniAppConfig:configList) {
                try {
                    String result = WxAppHelper.SINGLETON.getweAnalysis(miniAppConfig.getAppId(),miniAppConfig.getAppSecret(),beginDate,endDate);
                    VisitPageDto visitPageDto = objectMapper.readValue(result, VisitPageDto.class);
                    if(visitPageDto!=null) {
                        List<MiniVisitPageDto> list = visitPageDto.getList();
                        String ref_date = visitPageDto.getRef_date();
                        log.info("ref_date:{}",ref_date);
                        if(list!=null && list.size()>0) {
                            for (MiniVisitPageDto miniVisitPageDto : list) {
                                String page_path = miniVisitPageDto.getPage_path();
                                log.info("page_path:{}", page_path);
                                if (page_path.indexOf("?promotionCodeId") != -1) {
                                    String[] codeIds = page_path.split("promotionCodeId=");
                                    log.info("codeIds length:{}", codeIds.length);
                                    if (codeIds.length > 1) {
                                        //保存推广码记录
                                        savePromotionCodeVisitPage(miniVisitPageDto, codeIds[1], ref_date);
                                        log.info("promotionCodeId:{}", codeIds[1]);
                                    }
                                }
                                //保存访问记录
                                saveVisitPageLog(miniVisitPageDto, ref_date);
                            }
                        }
                    }
                } catch (Exception e) {
                    log.info("syncData error message:{}",e.getMessage());
                }
            }
        }
    }

    /**
     * 保存推广码记录
     * @param miniVisitPageDto
     * @param promotoinCodeId
     */
    private void savePromotionCodeVisitPage(MiniVisitPageDto miniVisitPageDto,String promotoinCodeId,String ref_date) {
        WxappVisitPage wxappVisitPage = new WxappVisitPage();
        wxappVisitPage.setPagePath(miniVisitPageDto.getPage_path());
        wxappVisitPage.setPageVisitPv(miniVisitPageDto.getPage_visit_pv());
        wxappVisitPage.setPageVisitUv(miniVisitPageDto.getPage_visit_uv());
        wxappVisitPage.setPageStaytimePv(miniVisitPageDto.getPage_staytime_pv());
        wxappVisitPage.setEntrypagePv(miniVisitPageDto.getEntrypage_pv());
        wxappVisitPage.setExitpagePv(miniVisitPageDto.getExitpage_pv());
        wxappVisitPage.setPageSharePv(miniVisitPageDto.getPage_share_pv());
        wxappVisitPage.setPageShareUv(miniVisitPageDto.getPage_share_uv());
        wxappVisitPage.setPromotionCodeId(new Long(promotoinCodeId));
        wxappVisitPage.setOperateDate(DateUtils.string2Date(ref_date));
        wxappVisitPageRepository.save(wxappVisitPage);
    }

    /**
     * 保存访问记录
     * @param miniVisitPageDto
     */
    private void saveVisitPageLog(MiniVisitPageDto miniVisitPageDto, String ref_date) {
        WxappVisitPageLog wxappVisitPageLog = new WxappVisitPageLog();
        wxappVisitPageLog.setPagePath(miniVisitPageDto.getPage_path());
        wxappVisitPageLog.setPageVisitPv(miniVisitPageDto.getPage_visit_pv());
        wxappVisitPageLog.setPageVisitUv(miniVisitPageDto.getPage_visit_uv());
        wxappVisitPageLog.setPageStaytimePv(miniVisitPageDto.getPage_staytime_pv());
        wxappVisitPageLog.setEntrypagePv(miniVisitPageDto.getEntrypage_pv());
        wxappVisitPageLog.setExitpagePv(miniVisitPageDto.getExitpage_pv());
        wxappVisitPageLog.setPageSharePv(miniVisitPageDto.getPage_share_pv());
        wxappVisitPageLog.setPageShareUv(miniVisitPageDto.getPage_share_uv());
        wxappVisitPageLog.setRefDate(ref_date);
        wxappVisitPageLogRepository.save(wxappVisitPageLog);
    }
}
